// pages/home-page/audioCourse/audioCourse.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    audioUrl: "",
    courseId: "1919873720801820672",
    toView: "ff",
    playType: [
      {
        icon: "icon-shunxubofang",
        name: "顺序播放",
      },
      {
        icon: "icon-liebiaoxunhuan",
        name: "列表循环",
      },
      {
        icon: "icon-xunhuanbofang",
        name: "循环播放",
      },
    ],
    currentPlayType: 0,
    changePlayTypeTimer: "",
    courseChangeTimer: "",
    changePlayTyping: false,
    scrollViewHeight: 200,
    courseList: [],
    courseSummary: {},
    currentPlayCourse: {
      index: 0,
      isPlay: false,
    },
    innerAudio: {},
    isChapterEmpty: false,
    isCourseEmpty: false,
    backgroundAudioManager: null,
    isFirstPlay: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id = options.id || ''
    this.getCourseList(id);
    this.calcScrollViewHeight();
    this.data.innerAudio = this.selectComponent("#innerAudio");
  },
  calcScrollViewHeight() {
    console.log(app.globalData.systemInfo);
    let windowHeight = app.globalData.systemInfo.windowHeight;
    let bottomSafeHeight =
      app.globalData.systemInfo.screenHeight -
      app.globalData.systemInfo.safeArea.bottom;
    const query = wx.createSelectorQuery();
    query.select("#course-list").boundingClientRect((res) => {
      console.log("#course-list", res);
      if (res) {
        this.setData({
          scrollViewHeight: windowHeight - res.top - bottomSafeHeight,
        });
      }
    });
    query.exec();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  goToFeedback() {
    if (this.data.currentPlayCourse.isPlay === true) {
      //跳转暂停
      this.playStatusChange();
    }
    wx.navigateTo({ url: "/myself/pages/create-feedback/createFeedback" });
  },

  audioOnNextEvent() {
    this.courseChange("next");
    console.log("this.courseChange(next)");
  },
  audioOnPrevEvent() {
    this.courseChange("prev");
    console.log("this.courseChange(prev)");
  },
  audioOnPauseEvent() {
    if (this.data.currentPlayCourse.isPlay === true) {
      this.setData({
        "currentPlayCourse.isPlay": false,
      });
    }
  },
  audioOnStopEvent() {
    if (this.data.currentPlayCourse.isPlay === true) {
      this.setData({
        "currentPlayCourse.isPlay": false,
      });
    }
  },
  audioOnPlayEvent() {
    if (this.data.currentPlayCourse.isPlay === false) {
      this.setData({
        "currentPlayCourse.isPlay": true,
      });
    }
  },
  //更改播放方式
  changePlayType() {
    console.log("changePlayType");
    this.data.currentPlayType += 1;
    if (this.data.currentPlayType >= 3) {
      this.data.currentPlayType = 0;
    }
    this.setData({
      currentPlayType: this.data.currentPlayType,
    });
    this.changePlayTypeApi();
  },
  changePlayTypeApi() {
    if (this.data.changePlayTyping) return; //接口调用中...
    clearTimeout(this.data.changePlayTypeTimer);
    this.data.changePlayTypeTimer = setTimeout(async () => {
      //防抖
      this.data.changePlayTyping = true;
      try {
        let res = await app.api.post({
          url: "audio_chapter_playOrder",
          data: {
            audioCourseId: this.data.courseSummary.audioCourseId,
            playOrder: this.data.currentPlayType + "",
          },
        });
        this.data.changePlayTyping = false;
      } catch (e) {
        this.data.changePlayTyping = false;
      }
    }, 200);
  },
  //更改播放的课程
  courseChange(e) {
    console.log("courseChange1");
    //更改状态
    this.data.isFirstPlay = false;
    clearTimeout(this.data.courseChangeTimer);
    this.data.courseChangeTimer = setTimeout(() => {
      //防抖
      console.log("courseChange2");
      let direction = e.currentTarget ? e.currentTarget.dataset.direction : e;
      let index = this.data.currentPlayCourse.index;
      console.log(index);
      if (direction == "prev") {
        index -= 1;
        if (index < 0) {
          index = 0;
          this.setData({
            "currentPlayCourse.index": index,
          });
          return;
        }
      } else {
        let length = this.data.courseList.length;
        index += 1;

        if (index >= length) {
          index = length - 1;
          this.setData({
            "currentPlayCourse.index": index,
          });
          return;
        }
      }
      console.log("courseChange");
      console.log(direction);
      this.changeCoursePlayStatus(index);
    }, 200);
  },
  //更改课程播放状态
  changeCoursePlayStatus(e) {
    //更改状态
    this.data.isFirstPlay = false;
    let index = e.currentTarget ? e.currentTarget.dataset.index : e;
    let audioUrl = "";
    if (index === this.data.currentPlayCourse.index) {
      this.data.currentPlayCourse.isPlay = !this.data.currentPlayCourse.isPlay;
    } else {
      audioUrl = this.data.courseList[index].ttsUrl;
      this.data.currentPlayCourse.index = index;
      this.data.currentPlayCourse.isPlay = true;
    }
    this.setData({
      currentPlayCourse: this.data.currentPlayCourse,
      toView: "courseid-" + this.data.courseList[index].chapterId,
    });
    this.playInnerAudioStatusChange(this.data.courseList[index]);
    this.changeCourseApi(this.data.courseList[index].chapterId);
  },
  //告知后端正在播放的课程
  async changeCourseApi(audioChapterId) {
    let res = await app.api.post({
      url: "audio_chapter_start",
      data: {
        audioCourseId: this.data.courseSummary.audioCourseId,
        audioChapterId: audioChapterId,
      },
    });
  },
  playStatusChange() {
    this.data.currentPlayCourse.isPlay = !this.data.currentPlayCourse.isPlay;
    this.setData({
      currentPlayCourse: this.data.currentPlayCourse,
    });
    this.playInnerAudioStatusChange();
    //进入本页面的首次播放
    if (
      this.data.currentPlayCourse.isPlay === true &&
      this.data.isFirstPlay === true
    ) {
      this.data.isFirstPlay = false;
    }
  },
  playInnerAudioStatusChange(course) {
    let innerAudio = this.selectComponent("#innerAudio");

    if (course) {
      innerAudio.initAudio(course);
    }
    if (this.data.currentPlayCourse.isPlay) {
      if (innerAudio.data.innerAudioContext) {
        innerAudio.goPlay();
      } else {
        innerAudio.initAudio(
          this.data.courseList[this.data.currentPlayCourse.index]
        );
      }
    } else {
      console.log("goPause");
      innerAudio.goPause();
    }
  },
  //获取课程列表
  async getCourseList(id) {
    try {
      let res = await app.api.post({
        url: "audio_course_detail",
        data: { audioCourseId: id },
      });
      console.log("getCourseList", res);
      let list = res.audioChapterDetailResps;
      delete res.audioChapterDetailResps;
      let isChapterEmpty = false;
      let isCourseEmpty = false;
      if (list && list.length > 0) {
        isChapterEmpty = false;
      } else {
        isChapterEmpty = true;
      }
      if (res.audioCourseId) {
        isCourseEmpty = false;
      } else {
        isCourseEmpty = true;
      }
      this.setData({
        courseSummary: res,
        courseList: list,
        isChapterEmpty: isChapterEmpty,
        isCourseEmpty: isCourseEmpty,
      });
      if (!isChapterEmpty) {
        this.setData({
          currentPlayType: parseInt(res.playOrder ? res.playOrder : 0),
          audioUrl: list[res.audioChapterPlayingIndex].ttsUrl,
          "currentPlayCourse.index": res.audioChapterPlayingIndex,
          toView: "courseid-" + list[res.audioChapterPlayingIndex].chapterId,
        });
        console.log(this.data);
        //this.data.innerAudio.initAudio(list[res.audioChapterPlayingIndex]);
      }
    } catch (e) {
      console.log(e);
    }
  },
  scrolltolower() {},
  scroll() {},
  //音频结束事件
  audioOnEndEvent() {
    let innerAudio = this.selectComponent("#innerAudio");
    let index = this.data.currentPlayCourse.index;
    let length = this.data.courseList.length;
    console.log(this.data.courseList);
    console.log(index);
    this.courseFinishApi(this.data.courseList[index].chapterId);
    switch (this.data.currentPlayType) {
      case 0: //顺序
        index += 1;
        console.log();
        if (index < length) {
          this.changeCoursePlayStatus(index);
          console.log("this.changeCoursePlayStatus(index);");
        } else {
          this.data.currentPlayCourse.isPlay =
            !this.data.currentPlayCourse.isPlay;
          this.setData({
            currentPlayCourse: this.data.currentPlayCourse,
          });
          innerAudio.goPause();
        }
        break;
      case 1: //列表
        index += 1;
        if (index >= length) {
          index = 0;
        }
        this.changeCoursePlayStatus(index);
        break;
      case 2: //自循环
        //innerAudio.setSeek(0);
        innerAudio.initAudio(this.data.courseList[index]);
        break;
    }
  },
  //告知后端课程完成
  async courseFinishApi(audioChapterId) {
    let res = await app.api.post({
      url: "audio_chapter_end",
      data: {
        audioCourseId: this.data.courseSummary.audioCourseId,
        audioChapterId: audioChapterId,
      },
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("onUnload");
    let innerAudio = this.selectComponent("#innerAudio");
    console.log(innerAudio);
    innerAudio.goPause();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
